package com.example.wanbaqian.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Paint;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Display;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.wanbaqian.R;
import com.example.wanbaqian.base.BaseActivity;
import com.example.wanbaqian.config.CommonValue;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static android.content.Context.TELEPHONY_SERVICE;


/**
 * Created by Administrator on 2016/11/15 0015.
 */

public class BaseUtils {

    /**
     * 设置中间的横线并且设置抗锯齿
     *
     * @param textView
     */
    public static void setTextViewLine(TextView textView) {
        textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    }

    /**
     * @param context
     * @param content
     * @param start   开始的位置 包括开始的
     * @param end     结束的位置 不包括结束的
     * @return
     */
    public static SpannableStringBuilder setTextColor(Context context, String content, int start, int end, int color) {
        SpannableStringBuilder builder = new SpannableStringBuilder(content);
        ForegroundColorSpan span = new ForegroundColorSpan(ContextCompat.getColor(context, color));
        builder.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return builder;
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
        /*
         * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
		 * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
		 * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
		 */
        String telRegex = "[1][34578]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles))
            return false;
        else
            return mobiles.matches(telRegex);
    }

    /**
     * 返回手机号码
     */
    private static String[] telFirst = "134,135,136,137,138,139,150,151,152,157,158,159,130,131,132,155,156,133,153,180,182,185,186,187,188".split(",");

    public static String getTel() {
        int index = getNum(0, telFirst.length - 1);
        String first = telFirst[index];
        String second = "****";
//        String second=String.valueOf(getNum(1,888)+10000).substring(1);
        String third = String.valueOf(getNum(1, 9100) + 10000).substring(1);
        return first + second + third;
    }

    public static int getNum(int start, int end) {
        return (int) (Math.random() * (end - start + 1) + start);
    }


    /**
     * 获取VersionCode
     *
     * @param context
     * @return
     */
    public static String geVersionCode(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            return "1.0.0";
        }
    }

    /**
     * 得到状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return context.getResources().getDimensionPixelSize(resourceId);
        }
        return 0;
    }

    public static float dp2px(Resources resources, float dp) {
        final float scale = resources.getDisplayMetrics().density;
        return dp * scale + 0.5f;
    }

    public static float sp2px(Resources resources, float sp) {
        final float scale = resources.getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

    /**
     * 跳转qq
     *
     * @param context
     * @return
     */
    public static String gotoQQ(Context context) {
        try {
            context.getPackageManager().getApplicationInfo("com.tencent.mobileqq",
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=" + CommonValue.HELP_QQ + "&version=1")));
        } catch (PackageManager.NameNotFoundException e) {
            return "客服为qq在线，联系客服请先安装qq";
        }
        return "";
    }

    /**
     * 显示用户头像
     *
     * @param context
     * @return
     */
    public static void loadImageForUserIcon(Context context, String url, ImageView imageView) {
        Glide.with(context).load(url).error(R.drawable.default_usericon).into(imageView);
    }

    /**
     * String当为null的时候返回""
     *
     * @param
     * @return
     */
    public static String isNull(String text) {
        if (TextUtils.isEmpty(text))
            return "";
        else
            return text;
    }

    /**
     * 获取屏幕的高宽
     *
     * @param
     * @return
     */
    public static int getScreen(Context context, boolean isWidth) {
        Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
        if (isWidth)
            return display.getWidth();
        else
            return display.getHeight();
    }

    /**
     * 跳转手机通讯录 选择联系人 并返回联系人信息
     *
     * @param context
     * @param uri
     * @return
     */
    public static String[] getPhoneContacts(Context context, Uri uri) {
        String[] contact = new String[2];
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null && cursor.getCount() != 0) {
            cursor.moveToFirst();
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null && phone.getCount() != 0) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            } else {
                contact[1] = "";
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    /**
     * 获取手机通讯录
     *
     * @param context
     * @return
     */
    public static List<Map<String, String>> readContact(final Context context) {
        final List<Map<String, String>> list = new ArrayList<>();
        BaseActivity.requestPermission(CommonValue.REQUEST_CODE1, new BaseActivity.PermissionListeren() {
            @Override
            public void onGranted(int requestCode) {
                try {
                    Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null, null, null, null);
                    Log.i("cursor", "onGranted: " + cursor.getCount());
                    while (cursor.moveToNext()) {
                        Map<String, String> map = new HashMap<>();
                        map.put("name", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
                        map.put("phone", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                        list.add(map);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onDenied(int requestCode, List<String> deniedPermissions, List<String> noReminderPermissions) {
            }
        }, Manifest.permission.READ_CONTACTS);
        return list;
    }

    /**
     * 唯一的设备ID：
     * GSM手机的 IMEI 和 CDMA手机的 MEID.
     *
     * @param mContext
     * @return
     */
    public static String getIMEI(final Context mContext) {
        final TelephonyManager[] tm = {null};
        BaseActivity.requestPermission(CommonValue.REQUEST_CODE1, new BaseActivity.PermissionListeren() {
            @Override
            public void onGranted(int requestCode) {
                tm[0] = (TelephonyManager) mContext.getSystemService(TELEPHONY_SERVICE);
            }

            @Override
            public void onDenied(int requestCode, List<String> deniedPermissions, List<String> noReminderPermissions) {

            }
        }, Manifest.permission.READ_PHONE_STATE);
        return null != tm[0] ? tm[0].getDeviceId() : "IMEI获取失败";
    }

    /**
     * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为1,英文字符长度为0.5
     *
     * @param s 需要得到长度的字符串
     * @return int 得到的字符串长度
     */
    public static double getLength(String s) {
        double valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        // 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1
        for (int i = 0; i < s.length(); i++) {
            // 获取一个字符
            String temp = s.substring(i, i + 1);
            // 判断是否为中文字符
            if (temp.matches(chinese)) {
                // 中文字符长度为1
                valueLength += 1;
            } else {
                // 其他字符长度为0.5
                valueLength += 0.5;
            }
        }
        //进位取整
        return Math.ceil(valueLength);
    }



    /**
     * 正则表达式：验证邮箱
     */
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    /**
     * 校验邮箱
     *
     * @param email
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isEmail(String email) {
        return Pattern.matches(REGEX_EMAIL, email);
    }

}
